
import context from '@/main.js'

import { getQnToken2, getQnUploadFile, uploadQiNinUrl } from '@/api/qiniu.js'
const bucket = require('@/config/config').bucket
const urlUpload = require('@/config/config').urlUpload

/*
  自定义上传七牛方法(不裁剪)
*/
export const uploadImgQiniu2 = (file, key) => {
  return new Promise(async resove => {
    let { data: token } = await getQnToken2(bucket, key)
    let formData = new FormData();
    formData.append("token", token);
    formData.append("key", key);
    formData.append("file", file);
    let result = await getQnUploadFile(formData)
    resove(`${urlUpload}${result.key}`);
  })
}

/*
  @desc:文件上传七牛服务器
  @params:{
    file:文件对象
  }
  @return:上传后的七牛文件链接
*/
export const uploadQnFile = (file) => {
  return new Promise(async (resove) => {
    const res = await getQnToken2(bucket, file.name);
    var formData = new FormData();
    formData.append("token", res.data);
    formData.append("key", file.name);
    formData.append("file", file.raw);
    let result = await getQnUploadFile(formData);
    resove(`${urlUpload}${result.key}`);
  });
}

/*
  七牛sdk上传（裁剪）
*/
export const uploadImgQn = (file, key) => {
  return new Promise(async (resolve, reject) => {
    const { data: token } = await getQnToken2(bucket, key)
    const options = {
      quality: 0.8,
      noCompressIfLarger: true,
      maxWidth: 1200,
      maxHeight: 618
    }
    const config = {
      useCdnDomain: true,
      disableStatisticsReport: true
    }
    const putExtra = {
    }
    context.qiniu.compressImage(file, options).then(data => {
      const observable = context.qiniu.upload(data.dist, key, token, putExtra, config)
      const subscription = observable.subscribe(observer) // 上传开始
    })
    const observer = {
      next(res) {
        console.log(res, 'next')
        // ...
      },
      error(err) {
        console.log(err, 'err')
        // ...
      },
      complete(res) {
        resolve(`${urlUpload}${res.key}`)
        console.log(`${urlUpload}${res.key}`, 'complete')
      }
    }
  })
}

/*
  外链上传
*/
export const uploadOutImg = ({ resUrl, key }) => {
  return new Promise(async resolve => {
    const res = await uploadQiNinUrl({ resUrl, key, bucket })
    resolve(`${urlUpload}${res.data.key}`)
  })
}


